<template>
  <div>
    <el-container class="index-container">
      <!-- 侧边栏区域 -->
      <el-aside width="240px">
        <div class="category-header">
          <h3>指标类别</h3>
          <el-button type="primary" circle icon="Plus" @click="openCategoryDialog('add')" />
        </div>
        <ul class="category-list">
          <li v-for="category in categories" :key="category.id" :class="{ selected: selectedCategory === category.id }"
            @click="selectCategory(category.id)">
            <span>{{ category.type }}</span>
            <div>
              <el-button link type="primary" @click.stop="openCategoryDialog('edit', category)">编辑</el-button>
              <el-button link type="danger" @click.stop="deleteCategory(category.id)">删除</el-button>
            </div>
          </li>
        </ul>
      </el-aside>

      <!-- 主内容区域 -->
      <el-main>
        <div class="operation-bar">
          <el-input placeholder="请输入关键字" clearable v-model="searchKeyword" />
          <el-button type="primary" @click="openIndicatorDialog">+ 新增指标</el-button>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="batchDelete">批量删除指标</el-button>
        </div>

        <el-table
          :data="pagedIndicators"
          @selection-change="handleSelectionChange"
          height="calc(100% - 120px)"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="指标名称" width="180" />
          <el-table-column prop="rule" label="指标规则" />
          <el-table-column prop="scoreMaxline" label="上限" width="100" />
          <el-table-column prop="remark" label="备注" width="120" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button link type="primary" @click="editIndicator(row)">编辑</el-button>
              <el-button link type="danger" @click="deleteIndicator(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredIndicators.length"
          layout="prev, pager, next"
          class="mt-2"
        />
      </el-main>

      <!-- 指标类别编辑对话框 -->
      <el-dialog v-model="categoryDialogVisible" :title="categoryDialogType === 'add' ? '添加指标类别' : '编辑指标类别'" width="400px" @closed="resetCategoryForm">
        <el-form :model="categoryForm" ref="categoryFormRef" :rules="categoryRules" label-width="80px">
          <el-form-item label="类别名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCategory">确定</el-button>
        </template>
      </el-dialog>

      <!-- 新增/编辑指标对话框 -->
      <el-dialog v-model="indicatorDialogVisible" :title="editingIndicatorId ? '编辑考核指标' : '新增考核指标'" width="600px" @closed="resetIndicatorForm">
        <el-form :model="indicatorForm" ref="indicatorFormRef" :rules="indicatorRules" label-width="90px">
          <el-form-item label="指标名称" prop="name">
            <el-input v-model="indicatorForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="指标类别" prop="categoryId">
            <el-select v-model="indicatorForm.categoryId" placeholder="请选择" clearable>
              <el-option v-for="item in categories" :key="item.id" :label="item.type" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="考核规则" prop="rule">
            <el-input v-model="indicatorForm.rule" type="textarea" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="加分上限" prop="upperLimit">
            <el-input-number v-model="indicatorForm.upperLimit" :min="0" :max="100" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="indicatorForm.remark" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="indicatorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveIndicator">确定</el-button>
        </template>
      </el-dialog>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listZhibiaoleibie, addZhibiaoleibie, updateZhibiaoleibie, delZhibiaoleibie } from "@/api/jixiao/zhibiaoku/zhibiaoleibie.js"
import { listAssessment, addAssessment, updateAssessment, delAssessment } from "@/api/jixiao/zhibiaoku/zhibiao.js"

// 类别数据
const categories = ref([])
const selectedCategory = ref(null)
const selectCategory = (id) => {
  selectedCategory.value = id
}

// 类别对话框控制
const categoryDialogVisible = ref(false)
const categoryDialogType = ref('add') // 'add' or 'edit'
const categoryForm = reactive({ id: null, name: '' })
const editingCategoryId = ref(null)
const categoryFormRef = ref(null)
const categoryRules = {
  name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }]
}

const openCategoryDialog = (type, category) => {
  categoryDialogType.value = type
  if (type === 'edit') {
    categoryForm.name = category.type
    editingCategoryId.value = category.id
  } else {
    categoryForm.name = ''
    editingCategoryId.value = null
  }
  categoryDialogVisible.value = true
}
const resetCategoryForm = () => {
  categoryForm.name = ''
  editingCategoryId.value = null
  categoryFormRef.value && categoryFormRef.value.clearValidate()
}

const saveCategory = () => {
  categoryFormRef.value.validate(valid => {
    if (!valid) return
    if (categoryDialogType.value === 'add') {
      addZhibiaoleibie({ type: categoryForm.name }).then(() => {
        reShowAll()
        ElMessage.success('添加成功')
        categoryDialogVisible.value = false
      })
    } else {
      updateZhibiaoleibie({ id: editingCategoryId.value, type: categoryForm.name }).then(() => {
        reShowAll()
        ElMessage.success('编辑成功')
        categoryDialogVisible.value = false
      })
    }
  })
}

const deleteCategory = (id) => {
  delZhibiaoleibie(id).then(() => {
    reShowAll()
    ElMessage.success('删除成功')
    // 如果删除的是当前选中的类别，则重置选中
    if (selectedCategory.value === id) {
      selectedCategory.value = categories.value.length ? categories.value[0].id : null
    }
  })
}

// 指标数据
const indicators = ref([])

// 指标对话框控制
const indicatorDialogVisible = ref(false)
const indicatorForm = reactive({
  id: null,
  name: '',
  categoryId: null,
  rule: '',
  upperLimit: 80,
  remark: ''
})
const editingIndicatorId = ref(null)
const indicatorFormRef = ref(null)
const indicatorRules = {
  name: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择指标类别', trigger: 'change' }],
  rule: [{ required: true, message: '请输入考核规则', trigger: 'blur' }],
  upperLimit: [{ required: true, message: '请输入加分上限', trigger: 'change' }]
}

const openIndicatorDialog = (indicator) => {
  if (indicator) {
    editingIndicatorId.value = indicator.id
    indicatorForm.id = indicator.id
    indicatorForm.name = indicator.name
    indicatorForm.categoryId = indicator.typeId
    indicatorForm.rule = indicator.rule
    indicatorForm.upperLimit = indicator.scoreMaxline
    indicatorForm.remark = indicator.remark
  } else {
    editingIndicatorId.value = null
    indicatorForm.id = null
    indicatorForm.name = ''
    indicatorForm.categoryId = selectedCategory.value
    indicatorForm.rule = ''
    indicatorForm.upperLimit = 80
    indicatorForm.remark = ''
  }
  indicatorDialogVisible.value = true
}
const resetIndicatorForm = () => {
  indicatorForm.id = null
  indicatorForm.name = ''
  indicatorForm.categoryId = selectedCategory.value
  indicatorForm.rule = ''
  indicatorForm.upperLimit = 80
  indicatorForm.remark = ''
  indicatorFormRef.value && indicatorFormRef.value.clearValidate()
}

const editIndicator = (indicator) => {
  openIndicatorDialog(indicator)
}

const saveIndicator = () => {
  indicatorFormRef.value.validate(valid => {
    if (!valid) return
    if (editingIndicatorId.value) {
      updateAssessment({
        id: editingIndicatorId.value,
        name: indicatorForm.name,
        typeId: indicatorForm.categoryId,
        rule: indicatorForm.rule,
        scoreMaxline: indicatorForm.upperLimit,
        remark: indicatorForm.remark,
      }).then(() => {
        reShowAll()
        ElMessage.success('编辑成功')
        indicatorDialogVisible.value = false
      })
    } else {
      addAssessment({
        name: indicatorForm.name,
        typeId: indicatorForm.categoryId,
        rule: indicatorForm.rule,
        scoreMaxline: indicatorForm.upperLimit,
        remark: indicatorForm.remark,
      }).then(() => {
        reShowAll()
        ElMessage.success('添加成功')
        indicatorDialogVisible.value = false
      })
    }
  })
}

const deleteIndicator = (id) => {
  delAssessment(id).then(() => {
    reShowAll()
    ElMessage.success('删除成功')
  })
}

// 搜索和分页
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = 10
const selectedIds = ref([])

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const batchDelete = () => {
  if (selectedIds.value.length === 0) return
  // 这里建议后端支持批量删除
  Promise.all(selectedIds.value.map(id => delAssessment(id))).then(() => {
    reShowAll()
    ElMessage.success('批量删除成功')
    selectedIds.value = []
  })
}

const filteredIndicators = computed(() => {
  return indicators.value.filter(indicator => {
    const matchCategory = indicator.typeId == selectedCategory.value
    const matchKeyword = searchKeyword.value === '' ||
      indicator.name.includes(searchKeyword.value) ||
      indicator.rule.includes(searchKeyword.value)
    return matchCategory && matchKeyword
  })
})

const pagedIndicators = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredIndicators.value.slice(start, start + pageSize)
})

// 初始化加载
onMounted(() => {
  reShowAll()
})
function reShowAll() {
  listZhibiaoleibie().then(response => {
    categories.value = response.rows
    // 默认选中第一个
    if (!selectedCategory.value && categories.value.length) {
      selectedCategory.value = categories.value[0].id
    }
  })
  listAssessment().then(response => {
    indicators.value = response.rows
  })
}
</script>

<style scoped>
.index-container {
  height: 100vh;
  background-color: #fff;
}
.el-aside {
  border-right: 1px solid #eee;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
}
.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.category-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
.category-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.category-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.category-list li:hover {
  background-color: #f5f7fa;
}
.category-list li.selected {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 600;
}
.operation-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
.operation-bar .el-input {
  width: 300px;
}
.mt-2 { margin-top: 16px; }
</style>